import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, Modal, Input, message, Form } from 'antd';
import { DeleteOutlined, DownloadOutlined, SearchOutlined } from '@ant-design/icons';
import axios from 'axios';

const Images = () => {
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pullModalVisible, setPullModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [pullForm] = Form.useForm();

  useEffect(() => {
    fetchImages();
  }, []);

  const fetchImages = async () => {
    try {
      const response = await axios.get('/api/images');
      setImages(response.data);
    } catch (error) {
      message.error('获取镜像列表失败');
    }
  };

  const handlePullImage = async (values) => {
    try {
      setLoading(true);
      await axios.post('/api/images/pull', { imageName: values.imageName });
      message.success('镜像拉取中，请稍后刷新查看');
      setPullModalVisible(false);
      pullForm.resetFields();
      setTimeout(fetchImages, 3000);
    } catch (error) {
      message.error('拉取镜像失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (imageId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个镜像吗？此操作不可恢复。',
      onOk: async () => {
        try {
          await axios.delete(`/api/images/${imageId}`);
          message.success('镜像已删除');
          fetchImages();
        } catch (error) {
          message.error('删除镜像失败');
        }
      }
    });
  };

  const formatSize = (bytes) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const filteredImages = images.filter(image => 
    image.RepoTags?.some(tag => tag.toLowerCase().includes(searchText.toLowerCase()))
  );

  const columns = [
    {
      title: '镜像名称',
      dataIndex: 'RepoTags',
      key: 'name',
      render: (tags) => tags?.[0] || '<none>:<none>',
    },
    {
      title: '镜像ID',
      dataIndex: 'Id',
      key: 'id',
      render: (id) => id.substring(7, 19),
    },
    {
      title: '大小',
      dataIndex: 'Size',
      key: 'size',
      render: (size) => formatSize(size),
    },
    {
      title: '创建时间',
      dataIndex: 'Created',
      key: 'created',
      render: (created) => new Date(created * 1000).toLocaleString(),
    },
    {
      title: '标签',
      dataIndex: 'RepoTags',
      key: 'tags',
      render: (tags) => (
        <Space wrap>
          {tags?.map(tag => (
            <Tag key={tag}>{tag}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space>
          <Button
            danger
            icon={<DeleteOutlined />}
            size="small"
            onClick={() => handleDelete(record.Id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <h1>镜像管理</h1>
      <div style={{ marginBottom: 16, display: 'flex', gap: 16 }}>
        <Input.Search
          placeholder="搜索镜像名称"
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          style={{ width: 300 }}
        />
        <Button
          type="primary"
          icon={<DownloadOutlined />}
          onClick={() => setPullModalVisible(true)}
        >
          拉取镜像
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={filteredImages}
        rowKey="Id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 个镜像`,
        }}
      />
      <Modal
        title="拉取镜像"
        open={pullModalVisible}
        onCancel={() => setPullModalVisible(false)}
        footer={null}
      >
        <Form form={pullForm} onFinish={handlePullImage} layout="vertical">
          <Form.Item
            name="imageName"
            label="镜像名称"
            rules={[{ required: true, message: '请输入镜像名称' }]}
          >
            <Input placeholder="例如: nginx:latest, mysql:8.0" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              拉取
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Images;
